package service

import (
	"context"
	"forum/app/comment/internal/repository/db/dao"
	pb "forum/idl/pb/comment"
	"forum/pkg/e"
	"sync"
)

var CommentSrvIns *CommentSrv
var CommentSrvOnce sync.Once

type CommentSrv struct {
	pb.UnimplementedCommentServiceServer
}

func GetCommentSrv() *CommentSrv {
	CommentSrvOnce.Do(func() {
		CommentSrvIns = &CommentSrv{}
	})
	return CommentSrvIns
}

func (c *CommentSrv) CommentCreate(ctx context.Context, req *pb.CommentRequest) (resp *pb.CommentCommonResponse, err error) {
	resp = new(pb.CommentCommonResponse)
	resp.Code = e.SUCCESS
	err = dao.NewCommentDao(ctx).CreateComment(req)
	if err != nil {
		resp.Code = e.ErrorCommentCreate
		resp.Msg = e.GetMsg(int(resp.Code))
		resp.Data = err.Error()
		return
	}
	return
}

func (c *CommentSrv) CommentUpdate(ctx context.Context, req *pb.CommentRequest) (resp *pb.CommentCommonResponse, err error) {
	resp = new(pb.CommentCommonResponse)
	resp.Code = e.SUCCESS
	err = dao.NewCommentDao(ctx).UpdateComment(req)
	if err != nil {
		resp.Code = e.ErrorCommentUpdate
		resp.Msg = e.GetMsg(int(resp.Code))
		resp.Data = err.Error()
		return
	}
	return
}

func (c *CommentSrv) CommentDelete(ctx context.Context, req *pb.CommentRequest) (resp *pb.CommentCommonResponse, err error) {
	resp = new(pb.CommentCommonResponse)
	resp.Code = e.SUCCESS
	err = dao.NewCommentDao(ctx).DeleteComment(req)
	if err != nil {
		resp.Code = e.ErrorCommentDelete
		resp.Msg = e.GetMsg(int(resp.Code))
		resp.Data = err.Error()
		return
	}
	return
}

func (c *CommentSrv) CommentList(ctx context.Context, req *pb.CommentRequest) (resp *pb.CommentDetailResponse, err error) {
	resp = new(pb.CommentDetailResponse)
	resp.Code = e.SUCCESS
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}
	r, err := dao.NewCommentDao(ctx).ListComment(req)
	if err != nil {
		resp.Code = e.ERROR
		return
	}
	for i := range r {
		resp.CommentDetail = append(resp.CommentDetail, &pb.CommentModel{
			CommentID:  uint64(r[i].ID),
			PostID:     uint64(r[i].PostID),
			UserID:     uint64(r[i].UserID),
			Content:    r[i].Content,
			CreateTime: r[i].CreatedAt.Unix(),
			UpdateTime: r[i].UpdatedAt.Unix(),
		})
	}
	resp.Total = uint32(len(r))
	return
}

func (c *CommentSrv) CommentGet(ctx context.Context, req *pb.CommentRequest) (resp *pb.CommentDetailResponse, err error) {
	resp = new(pb.CommentDetailResponse)
	resp.Code = e.SUCCESS
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}
	r, err := dao.NewCommentDao(ctx).ListCommentByUserID(req)
	if err != nil {
		resp.Code = e.ERROR
		return
	}
	for i := range r {
		resp.CommentDetail = append(resp.CommentDetail, &pb.CommentModel{
			CommentID:  uint64(r[i].ID),
			PostID:     uint64(r[i].PostID),
			UserID:     uint64(r[i].UserID),
			Content:    r[i].Content,
			CreateTime: r[i].CreatedAt.Unix(),
			UpdateTime: r[i].UpdatedAt.Unix(),
		})
	}
	resp.Total = uint32(len(r))
	return
}
